#include <assert.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void* th1(void* a)
{
  int err, signo, count = 0;
  sigset_t mask;

  printf("th1:id=0x%lx\n", (unsigned long)pthread_self());

  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);

  while (1) {
    err = sigwait(&mask, &signo);
    assert(err == 0);
    switch (signo) {
      case SIGINT:
        printf("\nth1:INT.\n");
        break;
      default:
        printf("\nth1:unexcepted signal %d.\n", signo);
        break;
    }
  }
}

void main_q(int a)
{
  printf("main:QUIT.\n");
}

int main()
{
  int err;
  sigset_t mask, old;
  pthread_t pt1, pt2;

  sigemptyset(&mask);
  sigaddset(&mask, SIGQUIT); /* 如果不屏蔽QUIT信号，则主线程会收到该信号 */
  sigaddset(&mask, SIGINT);
  err = pthread_sigmask(SIG_BLOCK, &mask, &old);
  assert(err == 0);

  signal(SIGQUIT, main_q);

  err = pthread_create(&pt1, NULL, th1, NULL);
  assert(err == 0);

  sleep(1);
  printf("main:send QUIT signal.\n");
  // 线程1未屏蔽QUIT信号，但没有处理程序，会返回给主线程
  pthread_kill(pt1, SIGQUIT);

  sleep(10);

  return 0;
}